#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/socket.h> /* AF_INET */
#include <netinet/in.h> /* sockaddr_in */
#include <netdb.h> /* gethostbyname */

#ifdef __PSP2__
#include <arpa/inet.h>
#include <sys/select.h>
#else
#endif

#ifdef __PSP2__
#define SERVER "www.yahoo.co.jp"
#else
#define SERVER "soft8-pc.rd.scei.sony.co.jp"
#endif

#define PORT 80
#define REQUEST  "GET / HTTP/1.0\r\n\r\n"
#define BUF_LEN  1024

int do_nettest()
{
	struct hostent *hostent;
	struct sockaddr_in server;

	int sock;

	char buf[BUF_LEN]; /* receive buffer */

	hostent = gethostbyname(SERVER); /* lookup IP */
	if (hostent == NULL ) {
	    printf("Cannot resolve %s.\n", SERVER);
	    return 0;
	}

	memset((void*)(&server), 0, sizeof(server));

	server.sin_family = AF_INET;
	/* server.sin_addr = hostent->h_addr */
	memcpy(&server.sin_addr, hostent->h_addr_list[0], hostent->h_length);
	server.sin_port = htons(PORT);

	if ( ( sock = socket(AF_INET, SOCK_STREAM, 0) ) < 0) {
	    fprintf(stderr, "Cannot make socket.\n");
	    return 0;
	}
	if ( connect(sock, (struct sockaddr *)&server, sizeof(server)) == -1) {
	    printf("Cannot connect.\n");
	    return 0;
	}
	printf("Connected to %s. sock = %08x\n", SERVER, (int)sock);

	send(sock, REQUEST, strlen(REQUEST), 0);

	if (1)
	{
		/* select */
		fd_set fds;
		while (1)
		{
			FD_ZERO(&fds);
			FD_SET(sock, &fds);
			int res = select(sock+1, &fds, NULL, NULL, NULL);
			printf("select %d\n", res);
			
			if (FD_ISSET(sock, &fds))
			{
				memset(buf, 0, BUF_LEN);
				int recv_size = recv(sock, buf, BUF_LEN, 0);
				if (recv_size > 0) {
				    printf("%s", buf);
				} else {
					printf("recv -> %08x\n", recv_size);
					break;
				}
			}
		}
	}
	else
	{
		/* Receive data */
		memset(buf, 0, BUF_LEN);
		while (recv(sock, buf, BUF_LEN, 0) > 0) {
		    printf("%s", buf);
			memset(buf, 0, BUF_LEN);
		}
	}



#ifdef __PSP2__
	closesocket(sock);
#else
	close(sock);
#endif
	return 0;
}

#ifndef __PSP2__
int main()
{
	do_nettest();
}
#endif
